package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/boyane/chartroom/common/message"
	"github.com/boyane/chartroom/server/models"
	"github.com/boyane/chartroom/server/utils"
	"net"
)

type User struct {
	Conn net.Conn
	UserId int
	UserName string
}

// 封装的登陆方法
func (this *User) ServerProcessLogin(mes *message.Message) (err error) {
	// 1. 将数据序列化
	var loginMes message.LoginMes
	err = json.Unmarshal([]byte(mes.Data), &loginMes)
	if err != nil{
		fmt.Println("json.Unmarshal fail err =", err)
		return
	}

	// 定义返回数据
	var resMes message.Message
	resMes.Type = message.LoginResMesType

	// 返回数据
	var data message.LoginResMes

	user, err := models.MyUserDao.Login(loginMes.UserId, loginMes.UserPwd)
	if err != nil{
		data.Code = 403
		data.Error = err.Error()
	}else{
		this.UserId = loginMes.UserId
		this.UserName = loginMes.UserName

		// 添加用户上线
		OnlineUsers.AddOnlineUser(this)
		// 通知所有在线用户 用户上线
		OnlineUsers.NotifyUserOnlineMes(loginMes.UserId)

		var onlineIds []int
		for k, _ := range OnlineUsers.GetAllOnlineUsers(){
			onlineIds = append(onlineIds, k)
		}
		data.OnlineIds = onlineIds
		data.Code = 200
		fmt.Println(user, "登陆成功")

	}

	// 序列化数据
	var bytes []byte
	bytes, err = json.Marshal(data)
	if err != nil{
		fmt.Println("json.Marshal fail err =", err)
		return
	}
	resMes.Data = string(bytes)

	bytes, err = json.Marshal(resMes)
	if err != nil{
		fmt.Println("json.Marshal fail err =", err)
		return
	}
	// 将组装好的数据发送给客户端
	ts := &utils.Transfer{}
	ts.Conn = this.Conn
	err = ts.WritePkg(bytes)
	if err != nil{
		fmt.Println("writePkg err =", err)
		return
	}
	return
}

// 封装用户注册方法
func (this *User) ServerProcessRegister(mes *message.Message) (err error) {
	// 将数据序列化
	var registerMes message.RegisterMes
	err = json.Unmarshal([]byte(mes.Data), &registerMes)
	if err != nil{
		fmt.Println("ServerProcessRegister -> json.Unmarshal err =", err)
		return
	}

	// 定义返回数据
	var resMes message.Message
	resMes.Type = message.RegisterResMesType

	// 返回数据
	var data message.RegisterResMes

	// 存入数据库中
	_, err = models.MyUserDao.Register(&registerMes)
	if err != nil{
		if err == models.ERROR_USER_EXISTS{
			data.Code = 403
			data.Error = models.ERROR_USER_EXISTS.Error()
		}else{
			data.Code = 405
			data.Error = "服务器未知错误"
		}
	}else{
		data.Code = 200
		data.Error = "注册成功"
	}

	var bytes []byte
	bytes, err = json.Marshal(data)
	if err != nil{
		fmt.Println("ServerProcessRegister -> json.Marshal err =", err)
	}
	resMes.Data = string(bytes)
	bytes, err = json.Marshal(resMes)
	if err != nil{
		fmt.Println("ServerProcessRegister -> json.Marshal err =", err)
	}
	ts := utils.Transfer{}
	ts.Conn = this.Conn
	err = ts.WritePkg(bytes)
	if err != nil{
		fmt.Println("ServerProcessRegister -> ts.WritePkg err =", err)
		return
	}
	return
}